package com.kuang.tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient02 {

    public static void main(String[] args) throws Exception {
        //1.创建一个Socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        //2.创建一个输出流
        OutputStream outputStream = socket.getOutputStream();
        //3.读取文件
        FileInputStream fileInputStream = new FileInputStream("Net/src/云同桌.png");

        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        //通知服务器，我已经结束了
        socket.shutdownOutput();
        //确定服务器接收完毕，才能断开连接
        InputStream inputStream = socket.getInputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        // 接收字符串使用字符串的管道流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        while ((len2=inputStream.read(buffer2))!=-1){
            byteArrayOutputStream.write(buffer2,0,len2);
        }
        System.out.println(byteArrayOutputStream.toString());
        //5.关闭资源
        byteArrayOutputStream.close();
        inputStream.close();
        outputStream.close();
        fileInputStream.close();
        socket.close();
    }
}
